<?php
/**
 * Created by PhpStorm.
 * User: dyane
 * Date: 2018/12/17
 * Time: 10:02
 */

namespace app\admin\controller;


use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class News extends Base
{
    /**
     * 文章列表页面
     * @return \think\response\View
     */
    public function index()
    {
        return $this->fetch('news/index');
    }
    public function newsList()
    {
        $param = $this->request->param();
        $where = [
            'n.is_delete'=>0,
            'n.type'=>1
        ];
        if (!empty($param['title'])) {
            $where['n.title'] = ['like','%'.$param['title'].'%'];
        }
        $count = Db::name('system_news')->where($where)->alias('n')->count();

        $page = isset($param['page']) ? intval($param['page']) : 1;
        $pageSize = isset($param['limit']) ? intval($param['limit']) : 10;
        $tol = ($page - 1) * $pageSize;
        $list = Db::name('system_news')
            ->field('n.id,n.title,n.add_time,n.update_time,n.view_count,n.desc')
            ->alias('n')
            ->where($where)
            ->limit($tol,$pageSize)
            ->order('n.add_time desc')
            ->select();
        foreach ($list as $key => $value){
            $list[$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
            $list[$key]['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
        }
        //返回数据
        return ["code" => "0", "msg" => "", "count" => $count, "data" => $list];
    }

    /**
     * 修改 文章数据页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsModifyPage()
    {
        $param = $this->request->param();

        if(!empty($param['id'])){
            $info = Db::name('system_news')->where(['id'=>$param['id']])->find();
            $this->assign('info',$info);
        }
        $this->assign('type',$param['type']);
        return $this->fetch('news/newsModifyPage');
    }
    /**
     * 修改|添加 文章数据
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function newsModify()
    {
        $param = $this->request->param();
        $rule = [
            'title|文章标题'=>'require',
            'content|文章内容'=>'require',
            'title_img|标题图片'=>'require',
            'desc|文章描述'=>'require',
//            'content_img|内容图片'=>'require'
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
            echo json_encode(['code'=>400,'msg'=>$validate->getError()]);die;
        }
        $data  = [
            'title'=>$param['title'],
            'content'=>$param['content'],
            'title_img'=>$param['title_img'],
            'desc'=>$param['desc'],
            'type'=>$param['type'],
//                'content_img'=>$param['content_img'],
            'update_time'=>time()
        ];
        if(!empty($param['id'])){
            $oldData = Db::name('system_news')->field('title_img')->where(['id'=>$param['id']])->find();
            if($oldData['title_img'] != $param['title_img']){
                $url = ROOT_PATH . 'public' . $oldData['title_img'];
                if(file_exists($url)){
                    unlink($url);
                }
            }
//            if($oldData['content_img'] != $param['content_img']){
//                $url = ROOT_PATH . 'public' . $oldData['content_img'];
//                if(file_exists($url)){
//                    unlink($url);
//                }
//            }
            $res = Db::name('system_news')->where(['id'=>$param['id']])->update($data);
            if($res){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>400,'msg'=>'操作失败']);
            }
        }else{
            $data['add_time'] = time();
            $user = Db::table('users')->where('is_delete',0)->select();
            try{
                Db::startTrans();
                if($data['type'] == 1){
                    $title = '新文章发布';
                    $content = '新文章发布,标题为'.$param['title'];
                }else{
                    $title = '信息公开发布';
                    $content = '信息公开发布,标题为'.$param['title'];
                }
                foreach ($user as $k =>$v){
                    Db::table('system_massages')->insert([
                        'title'=> $title,
                        'content'=> $content,
                        'add_time'=> time(),
                        'status'=> 0,
                        'is_delete'=> 0,
                        'type'=> 2,
                        'user_id'=> $v['id'],
                    ]);
                }
                Db::name('system_news')->insert($data);
                Db::commit();
                return json(['code'=>200,'msg'=>'操作成功']);
            }catch (Exception $e){
                Db::rollback();
                return json(['code'=>400,'msg'=>'操作失败']);
            }
        }
    }

    /***********************************************信息公开*********************************************************/
    public function open()
    {
        return view();
    }

    public function openList()
    {
        $param = $this->request->param();
        $where = [
            'n.is_delete'=>0,
            'n.type'=>2
        ];
        if (!empty($param['title'])) {
            $where['n.title'] = ['like','%'.$param['title'].'%'];
        }
        $count = Db::name('system_news')->where($where)->alias('n')->count();

        $page = isset($param['page']) ? intval($param['page']) : 1;
        $pageSize = isset($param['limit']) ? intval($param['limit']) : 10;

        $tol = ($page - 1) * $pageSize;
        $list = Db::name('system_news')
            ->field('n.id,n.title,n.add_time,n.update_time,n.view_count,n.desc')
            ->alias('n')
            ->where($where)
            ->limit($tol,$pageSize)
            ->order('n.add_time desc')
            ->select();
        foreach ($list as $key => $value){
            $list[$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
            $list[$key]['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
        }
        //返回数据
        return ["code" => "0", "msg" => "", "count" => $count, "data" => $list];
    }
    /***********************************************信息公开end*********************************************************/



    /**
     * 删除文章信息
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delNews()
    {
        $param = $this->request->param();
        $info = Db::name('system_news')->field('title_img,content_img')->where(['id'=>$param['id']])->find();
        if(!empty($info['title_img'])){
            $url = ROOT_PATH . 'public' . $info['title_img'];
            if(file_exists($url)){
                unlink($url);
            }
        }
        if(!empty($param['content_img'])){
            $url = ROOT_PATH . 'public' . $info['content_img'];
            if(file_exists($url)){
                unlink($url);
            }
        }
        $res = Db::name('system_news')->where(['id'=>$param['id']])->update(['is_delete'=>0]);
        if($res){
            echo json_encode(['code'=>200,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['code'=>400,'msg'=>'删除失败']);die;
        }
    }

    /**
     * 文章详情页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsInfo()
    {
        $param = $this->request->param();
        $info = Db::name('system_news')->where(['id'=>$param['id']])->find();
        $this->assign('info',$info);
        return view();
    }

    /**
     * 系统消息页面
     * @return \think\response\View
     */
    public function massageIndex()
    {
        return view();
    }

    /**
     * 系统消息列表数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function massageList()
    {
        $param = $this->request->param();
        $where = '1 = 1 and m.is_delete = 0';
        if (!empty($param['type'])) {
            $type = $param['type'] - 1;
            $where .= ' and m.type = ' . $type;
        }
        if (!empty($param['start_time'])) {
            $startTime = strtotime($param['start_time']);
            $where .= ' and m.note_time >= ' . $startTime;
        }
        if (!empty($param['end_time'])) {
            $endTime = strtotime($param['end_time']);
            $where .= ' and m.note_time <= ' . $endTime;
        }
        $count = Db::name('system_massages')->where($where)->alias('m')->count();
        $limit = Request::instance()->param('limit')?Request::instance()->param('limit'):10;
        $page = Request::instance()->param('page')?Request::instance()->param('page'):1;
        $tol = ($page - 1) * $limit;
        $list = Db::name('system_massages')
            ->field('m.id,m.content,m.add_time,m.update_time,m.note_time,m.type,m.title,u.user_name')
            ->alias('m')
            ->where($where)
            ->join('users u','u.id = m.user_id')
            ->limit($tol,$limit)
            ->order('m.id desc')
            ->select();
        foreach ($list as $key => $value){
            $list[$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
            $list[$key]['update_time'] = date('Y-m-d H:i:s',$value['update_time']);
            $list[$key]['note_time'] = date('Y-m-d H:i:s',$value['note_time']);
            if($value['type'] == 1){
                $list[$key]['type'] = '系统消息';
            }elseif($value['type'] == 2){
                $list[$key]['type'] = '订单消息';
            }else{
                $list[$key]['type'] = '客服消息';
            }
        }
        //返回数据
        return ["code" => "0", "msg" => "", "count" => $count, "data" => $list];
    }

    /**
     * 修改|添加 系统消息页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function massageModifyPage()
    {
        $param = $this->request->param();
        if(!empty($param['id'])){
            $info = Db::name('system_massages')->field('id,content,type,note_time,title,user_id')->where(['id'=>$param['id']])->find();
            $info['note_time'] = date('Y-m-d H:i:s',$info['note_time']);
            $info['type'] = $info['type'] + 1;
            $this->assign('info',$info);
        }
        $user = Db::name('users')->field('id,user_name')->order('id desc')->select();
        $this->assign('user',$user);
        return view();
    }

    /**
     * 修改|添加 系统消息
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function massageModify()
    {
        $param = $this->request->param();
        $rule = [
            'content|消息内容'=>'require',
            'type|消息类型'=>'require',
            'note_time|通知时间'=>'require',
            'title|消息标题'=>'require',
            'user_id|发送用户'=>'require'
        ];
        $validate = new Validate($rule);
        if(!$validate->check($param)){
            echo json_encode(['code'=>400,'msg'=>$validate->getError()]);die;
        }
        $type = $param['type'] - 1;
        if(!empty($param['id'])){
            $noteTime = strtotime($param['note_time']);
            $data = [
                'content'=>$param['content'],
                'type'=>$type,
                'update_time'=>time(),
                'note_time'=>$noteTime,
                'title'=>$param['title'],
                'user_id'=>$param['user_id']
            ];
            $res = Db::name('system_massages')->where(['id'=>$param['id']])->update($data);
        }else{
            $data = [
                'content'=>$param['content'],
                'type'=>$type,
                'note_time'=>strtotime($param['note_time']),
                'add_time'=>time(),
                'update_time'=>time(),
                'title'=>$param['title'],
                'user_id'=>$param['user_id']
            ];
            $res = Db::name('system_massages')->insert($data);
        }
        if($res){
            echo json_encode(['code'=>200,'msg'=>'操作成功']);die;
        }else{
            echo json_encode(['code'=>400,'msg'=>'操作失败']);die;
        }
    }

    /**
     * 删除系统消息数据
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delMassage()
    {
        $param = $this->request->param();
        $res = Db::name('system_massages')->where(['id'=>$param['id']])->update(['is_delete'=>1]);
        if($res){
            echo json_encode(['code'=>200,'msg'=>'删除成功']);die;
        }else{
            echo json_encode(['code'=>400,'msg'=>'删除失败']);die;
        }
    }
}